/*
 * @Description: axios
 * @Author: zhen.feng@leyantech.com
 * @Date: 2022-12-19 15:06:37
 */


import axios from "axios";
import router from "@/router";
axios.defaults.baseURL = process.env.VUE_APP_HOST;
axios.defaults.headers.post["Content-Type"] = "application/json";

// 请求拦截
axios.interceptors.request.use(
  (config: any) => {
    // Do something before request is sent
    const token = localStorage.getItem("token") as string;
    if (token && config.headers) {
      // eslint-disable-next-line no-param-reassign
      config.headers["sc-access-token"] = token;
    }
    return config;
  },
  (error: any) => {
    // Do something with request error
    return Promise.reject(error);
  }
);       

// 相应拦截
const withHeaders = ["/user/publicKey"];
axios.interceptors.response.use(
  (response: any) => {
    if (withHeaders.includes(response.config.url as any)) {
      return response;
    }
    if (response.headers["sc-access-token"]) {
      localStorage.setItem("token", response.headers["sc-access-token"]);
    }
    return response.data;
  },
  (error: any) => {
    const { response } = error;
    if (response.status === 401) {
      router.replace("/login");
    }
    return Promise.reject(error);
  }
);
